package com.kingsoft.dc.khaos.module.spark.model.TechCheck;

import com.kingsoft.dc.khaos.module.spark.util.DateTimeForamtUtil;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

public class KsyunDatetimeCheckRule extends KsyunCheckRule {
    private static final Pattern intPattern = Pattern.compile("[1-9][0-9]{0,3}"); //123
    private static final Set<String> SPERACIL_TYPE = new HashSet<String>();
    static{
        SPERACIL_TYPE.add("MMDD");
        SPERACIL_TYPE.add("MM");
            SPERACIL_TYPE.add("DD");
        SPERACIL_TYPE.add("MMDDHHMMSS");
    }
    private String dataType;
    private DateFormat dateFormat;
    public KsyunDatetimeCheckRule(String dataType){
        this.dataType = dataType;
    }


    @Override
    public Tuple4<String,String, KsyunErrorCode,String> check(String value) {
        String tepValue = value.trim();
        if(tepValue.length()==0) //空字符串不做校验
            return null;
        else if(tepValue.length() != dataType.length()){
            if(dataType.indexOf("HH")>0)
                throw new KsyunTechCheckException(KsyunErrorCode.TIME_LEGAL_CHECK,"规则："+dataType+ "实际值：" + value);
            else
                throw new KsyunTechCheckException(KsyunErrorCode.DATE_LEGAL_CHECK,"规则："+dataType+ "实际值：" + value);
        }else if(dataType.equals("YYYY")){
            if(intPattern.matcher(tepValue).matches()){
                return null;
            }else{
                throw new KsyunTechCheckException(KsyunErrorCode.DATE_LEGAL_CHECK,"规则："+dataType+ "实际值：" + value);
            }
        }
        if(this.dateFormat == null){
            this.dateFormat = DateTimeForamtUtil.getFormater(dataType);
        }
        try {
            this.dateFormat.parse(tepValue);
        } catch (ParseException e) {
            if(SPERACIL_TYPE.contains(dataType)){
                throw new KsyunTechCheckException(KsyunErrorCode.SPECIAL_DATE_LEGAL_CHECK,"规则："+dataType+ "实际值：" + value);
            }else if(this.dataType.equals("YYYYMMDD") && tepValue.equals("99999999") ){
                return new Tuple4(value,"29991231", KsyunErrorCode.DATE_DEFAULT_CHECK,"将99999999替换成29991231");
            }else if(dataType.indexOf("HH")>0)
                throw new KsyunTechCheckException(KsyunErrorCode.TIME_LEGAL_CHECK,"规则："+dataType+ "实际值：" + value);
            else
                throw new KsyunTechCheckException(KsyunErrorCode.DATE_LEGAL_CHECK,"规则："+dataType+ "实际值：" + value);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(intPattern.matcher("11").matches());
    }
}
